/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.task.setup;

import edu.cmu.lti.sepia.data.db.SQL;
import edu.cmu.lti.sepia.data.resource.ResourceManager;

public class DBInitializer {
	
	private static String sharedSqlPath = "sql/init_shared_db.sql";
	private static String taskSqlPath = "sql/init_task_db.sql";

	public static String createSharedDB( SQL sql, String projectName ) {
		// db name now look like `sepia_aclia_shared` 
		projectName = cannonicalize( projectName );
		
		String queries = ResourceManager.readResource( sharedSqlPath );
		queries = queries.replaceAll("`sepia_shared`", "`sepia_"+projectName+"_shared`");
		
		return createDB( sql, queries );
	}
	
	public static String createTaskDB( SQL sql, String projectName, String taskName ) {
		// db name now look like `sepia_aclia_ja-training` 
		projectName = cannonicalize( projectName );
		taskName    = cannonicalize( taskName );
		
		String sqls = ResourceManager.readResource( taskSqlPath );
		sqls = sqls.replaceAll("`sepia_task`", "`sepia_"+projectName+"_"+taskName+"`");
		
		return createDB( sql, sqls );
	}
	
	private static String cannonicalize( String text ) {
		return text;
		//return text.replaceAll("[^0-9a-zA-Z_\\-]+", "_").toLowerCase();
	}
	
	private static String createDB( SQL sql, String queries ) {
		StringBuilder sb = new StringBuilder();

		queries = queries.replaceAll("--.*?\n", "");
		String[] sqlStatements = queries.split(";");
		for ( String sqlStatement : sqlStatements ) {
			sqlStatement = sqlStatement.replaceAll("[\r\n]", " ");
			sqlStatement = sqlStatement.replaceAll("[ ]+", " ");
			sqlStatement = sqlStatement.replaceAll("^[ ]+", "").trim();
			if ( sqlStatement.length()==0 ) continue;
			sb.append( "Executing: "+sqlStatement+"\n" );
//			try {
				sb.append( sql.execute( sqlStatement ) );
//			} catch ( SQLException e ) {
//				sb.append( ExceptionUtil.exceptionToString(e) );
//			}
			sb.append( "\n" );
		}
		return sb.toString();
	}
	
	public static void main(String[] args) throws Exception {
	  SQL sql = new SQL();
		createSharedDB(sql, "test" );
		sql.close();
	}
	
}
